package com.ydgk.interceptor;

import com.ydgk.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author kfstart
 * @descrption
 * @create 2020-01-07 14:39
 */
public class PortalLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        // 判断用户是否登录，如果用户登录了该方法就返回true 否则返回false
        // 如何判断用户是否登录。
        // 判断 Session 域中是否存在对应的 user 属性
        HttpSession session = httpServletRequest.getSession();

        User user = (User) session.getAttribute("user");

        if (user != null) {
            return true;
        } else {
            String path = httpServletRequest.getContextPath();
            //重定向到一个错误页面
            httpServletResponse.sendRedirect(path + "/toPortalLogin");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
